<?php

namespace frontend\controllers;

use Yii;
use common\helpers\Curl;
use frontend\models\User;
use frontend\models\UserCoupon;
use frontend\models\Product;
use frontend\models\Order;
use frontend\models\ProductPrice;
use frontend\models\DataAll;
use frontend\models\Retail;
use frontend\models\UserCharge;
use console\models\GatherForeign;
use common\models\ProductParam;
use common\helpers\FileHelper;
use common\helpers\Json;

class SiteController extends \frontend\components\Controller
{
    public function beforeAction($action)
    {
        if(!config('web_state', 1)) {
            return $this->redirect('/user/maintain');
        }

        $actions = ['ajax-update-status', 'wxtoken', 'wxcode', 'test', 'captcha', 'login' , 'register', 'forget', 'zynotify', 'verify-code', 'zsnotify', 'bxnotify', 'new-bxnotify', 'notify', 'hmbank-alipaynotify', 'hm-alipaynotify', 'yifu-notify'];
        if (user()->isGuest && !in_array($this->action->id, $actions)) {
            $this->redirect(['site/login']);
            return false;
            // $wx = session('wechat_userinfo');
            // if (!empty($wx)) {
            //     $user = User::find()->where(['open_id' => $wx['openid']])->one();
            //     $user->login(false);
            // } else {
            //     $code = get('code');
            //     if (empty($code)) {
            //         $this->redirect(['/wechart.php']);
            //         return false;
            //     } else {
            //         User::registerUser($code);
            //     }
            // }
        }
        if (!parent::beforeAction($action)) {
            return false;
        } else {
            return true;
        }
    }

    public function actionIndex()
    {   
        $this->view->title = '首页';
        //找三个上架的产品ON_SALE_YES
        $productArr = Product::getIndexProduct();
        foreach ($productArr as $key => $value) {
            $jsonArr[] = $value['table_name'];
        }
        $json = json_encode($jsonArr);
        reset($productArr);
        $pid = get('pid', key($productArr));
        //这条期货信息
        $product = Product::find()->andWhere(['id' => $pid])->with('dataAll')->one();

        $productPrice = ProductPrice::getSetProductPrice($pid);
        // $timeHtml = '交易时间：周一至周五，' . Product::getProductTradeTime($pid);
        $timeHtml = config('web_trade_time', '交易时间：周一至周五，9:00-23:00');
        //最新的这条期货数据集
        $newData = DataAll::newProductPrice($product->table_name);
        return $this->render('index', compact('product', 'newData', 'productArr', 'json', 'productPrice', 'timeHtml', 'pid'));
    }

    //期货的最新价格数据集
    public function actionAjaxNewProductPrice()
    {
        $json = post('data');
        //周末休市
        if (date('w') == 6 || date('w') == 0) {
            return error();
        }
        // $pidArr = json_decode($json);
        // $data = DataAll::find()->where(['in', 'name', $pidArr])->map('name', 'price');
        $data = json_decode(file_get_contents(Yii::getAlias('@webroot/' . 'price.json')));
        if (!empty($data)) {
            return success($data);
        }
        return error('无此期货数据！');
    }

    //买涨买跌
    public function actionAjaxBuyState()
    {
        if (strlen(u()->password) <= 1) {
            return $this->redirect(['site/setPassword']);
        }
        //如果要体现必须要有手机号
        if (strlen(u()->mobile) <= 10) {
            return $this->redirect(['site/setMobile']);
        }
        $data = post('data');
        $productPrice = ProductPrice::find()->where(['id' => $data['id']])->with(['product'])->one();
        $data = $productPrice->attributes;
        $data['name'] = $productPrice->product->name;
        //查找用户体验卷
        $couponType = UserCoupon::getNumberType(0);
        $coupon['couponNum'] = array_sum($couponType);
        $coupon['couponTypeHtml'] = $this->renderPartial('_couponList', compact('couponType' , 'coupon'));
        
        return success($data, $coupon);
    }

    //产品参数
    public function actionAjaxProductConfig()
    {
        $productId = post('id');
        // $string = Product::getProductTradeTime($productId);
        $string = config('web_trade_time', '交易时间：周一至周五，9:00-23:00');
        if (Product::isTradeTime($productId)) {
            $isTime = 1;
        } else {
           $isTime = -1; 
        }
        $productPrice = ProductPrice::getSetProductPrice($productId);
        $product = Product::find()->andWhere(['id' => $productId])->with('dataAll')->one();
        return success(['list' => $this->renderPartial('_unitList', compact('productPrice')), 'isTime' => $isTime, 'time' => $string, 'price' => $product->dataAll->price], $productPrice);
    }

    //产品单位参数
    public function actionAjaxProductUnit()
    {
        $productPrice = ProductPrice::findModel(post('id'));
        return success($productPrice->one_profit);
    }
    //设置交易密码
    public function actionAjaxSetPassword()
    {
        $data = trim(post('data'));
        if (strlen($data) < 6) {
            return error('交易密码长度不能少于6位！');
        }
        $user = User::findModel(u()->id);
        $user->password = $data;
        if ($user->hashPassword()->save()) {
            $user->login(false);
            return success();
        }
        return error('设置失败！');
    }

    //全局控制用户跳转链接是否设置了交易密码
    public function actionAjaxOverallPsd()
    {
        if (strlen(u()->password) <= 1) {
            // return error($this->renderPartial('_setPsd'));
            return success(url(['site/setPassword']), -1);
        }
        //如果要体现必须要有手机号
        if (strlen(u()->mobile) <= 10) {
            return success(url(['site/setMobile']), -1);
        }
        return success(post('url'));
    }

    //第一次设置交易密码
    public function actionSetPassword()
    {
        $this->view->title = '请设置交易密码';
        if (strlen(u()->password) > 1) {
            return $this->success(Yii::$app->getUser()->getReturnUrl(url(['site/index'])));
        }
        $model = User::findModel(u()->id);
        $model->scenario = 'setPassword';
        if ($model->load(post())) {
            if ($model->validate()) {
                $model->hashPassword()->save(false);
                return $this->success(Yii::$app->getUser()->getReturnUrl(url(['site/index'])));
            } else {
                return error($model);
            }
        }
        $model->password = '';

        return $this->render('setPassword', compact('model'));
    }

    //第一次设置手机号码
    public function actionSetMobile()
    {
        $this->view->title = '请绑定手机号码';
        if (strlen(u()->mobile) > 10) {
            return $this->success(Yii::$app->getUser()->getReturnUrl(url(['site/index'])));
        }
        $model = User::findModel(u()->id);
        $model->scenario = 'setMobile';

        if ($model->load(post())) {
            $model->username = $model->mobile;
            if ($model->verifyCode != session('verifyCode')) {
                return error('短信验证码不正确');
            }
            if ($model->validate()) {
                $model->save(false);
                session('verifyCode', '');
                return $this->success(Yii::$app->getUser()->getReturnUrl(url(['site/index'])));
            } else {
                return error($model);
            }
        }
        $model->mobile = '';

        return $this->render('setMobile', compact('model'));
    }

    public function actionRegister()
    {
        if (!user()->isGuest) {
            return $this->redirect(['site/index']);
        }
        $this->view->title = config('web_name') . '注册';
        $this->layout = 'empty';
        $model = new User(['scenario' => 'register']);

        if ($model->load(post())) {
            $model->username = $model->mobile;
            $model->face = config('web_logo', '');
            $model->open_id = date("Yhdhis") . rand(100000, 999999);
            if ($model->validate()) {
                $retail = Retail::find()->joinWith(['adminUser'])->where(['retail.code' => $model->code])->one();
                if (!empty($retail)) {
                    $model->admin_id = $retail->adminUser->id;
                } else {
                    return error('请填写正确的邀请码！');
                }
                $user_phone = User::find()->where(['username' => $model->mobile])->one();
                if(!empty($user_phone)) {
                    return error('手机号已注册！');
                }
                $model->hashPassword()->insert(false);
                $model->login(false);
                return success(url(['site/index']));
            } else {
                return error($model);
            }

            /*$model->username = $model->mobile;
            $model->account = 20;
            $wx = session('wechat_userinfo');
            if (!empty($wx)) {
                $model->face = $wx['headimgurl'];
                $model->open_id = $wx['openid'];
            }
            if ($model->validate()) {
                $retail = Retail::find()->joinWith(['adminUser'])->where(['retail.code' => $model->code])->one();
                $user_phone = User::find()->where(['username' => $model->mobile])->one();
                if(!empty($user_phone)) {
                    return error('已经注册了');
                }
                if (!empty($retail)){

                    $model->admin_id = $retail->adminUser->id;
                } else {
                    return error('请填写正确的邀请码！');
                }
                if (!empty($model->open_id)) {
                    $user = User::find()->where(['open_id' => $model->open_id])->one();
                    if (!empty($user)) {
                        $user->mobile = $model->mobile;
                        $user->username = $model->mobile;
                        $user->nickname = $model->nickname;
                        $user->password = $model->password;
                        $user->admin_id = $model->admin_id;
                        $user->account = 20;
                        $user->face = $model->face;
                        $user->hashPassword()->update(false);
                        $user->login(false);
                        return success(url(['site/index']));
                    }
                }
                $model->hashPassword()->insert(false);
                $model->login(false);
                return success(url(['site/index']));
                // return $this->goBack();
            } else {
                return error($model);
            }*/
        }
        //session微信数据
        /*User::getWeChatUser(get('code'));
        $wx = session('wechat_userinfo');
        $user = User::find()->where(['open_id' => $wx['openid'], 'username' => 0])->one();
        $model->code = '';
        if (!empty($user)) {
            $retail = Retail::find()->joinWith(['adminUser'])->where(['adminUser.id' => $user->admin_id])->one();
            $model->code = isset($retail)?$retail->code:'';
        }*/
        $user = User::registerUser2(get('pid'));
        $model->code = '';
        $model->pid = '';
        if ($user) {
            $model->code = $user[0];
            $model->pid = $user[1];
        }

        return $this->render('register', compact('model', 'user'));
    }

    public function actionLogin()
    {
        $this->view->title = config('web_name', '夕秀微盘') . '-登录';
        $this->layout = 'empty';
        $model = new User(['scenario' => 'login']);
        if (!user()->isGuest) {
            return $this->redirect(['site/index']);
        }
        if ($model->load(post())) {
            if ($model->login()) {
                return success(url('site/index'));
                // return $this->goBack();
            } else {
                return error($model);
            }
        }

        return $this->render('login', compact('model'));
    }

    public function actionWeChart()
    {
        $this->view->title = config('web_name') . '跳转';
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='. WX_APPID . '&redirect_uri=http%3a%2f%2f' . $_SERVER['HTTP_HOST'] . '/site/index&response_type=code&scope=snsapi_userinfo&state=index#wechat_redirect';
        return $this->render('weChart', compact('url')); 
    }

    public function actionForget()
    {
        $this->view->title = '忘记密码';
        $model = new User(['scenario' => 'forget']);
        $this->layout = 'empty';
        if ($model->load(post())) {
            $user = User::find()->andWhere(['mobile' => post('User')['mobile']])->one();
            if (!$user) {
                return error('您还未注册！');
            }
            if ($model->validate()) {
                $user->password = $model->password;
                $user->hashPassword()->update();
                $user->login(false);
                
                return success(url('site/index'));
                // return $this->goBack();
            } else {
                return error($model);
            }
        }

        return $this->render('forget', compact('model'));
    }
    //投资学院
    public function actionInvestSchool()
    {
        $this->view->title = '忘记密码';
        return $this->render('investSchool');
    }

    public function actionLogout()
    {
        user()->logout(false);

        return $this->redirect(['index']);
    }

    // public function actionVerifyCode()
    // {
    //     $mobile = req('mobile');
    //     // 生成随机数，非正式环境一直是1234
    //     $randomNum = YII_ENV_PROD ? rand(1024, 9951) : 1234;
    //     $res = sendsms($mobile, $randomNum);
    //     // $res = ['info' => 'OK', 'code' => 2];
    //     if ($res['code'] == 2) {
    //         // 记录随机数
    //         session('verifyCode', $randomNum, 1800);
    //         return success($res['info']);
    //     } else {
    //         return error($res['info']);
    //     }
    // }


    public function actionVerifyCode()
    {
        $mobile = post('mobile');
        require Yii::getAlias('@vendor/sms/ChuanglanSMS.php');
        // 生成随机数，非正式环境一直是1234
        $randomNum = YII_ENV_PROD ? rand(1024, 9951) : 1234;
        // $res = sendsms($mobile, $randomNum);
        if (!preg_match('/^1[34578]\d{9}$/', $mobile)) {
            return success('您输入的不是一个手机号！');
        }
        $ip = str_replace('.', '_', isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null);

        if (session('ip_' . $ip)) {
            return success('短信已发送请在60秒后再次点击发送！');
        }

        $sms = new \ChuanglanSMS();
        $result = $sms->sendSMS($mobile, '【'.config('web_sign', '源点云创').'】您好，您的验证码是' . $randomNum);
        $result = $sms->execResult($result);
        //$randomNum = 1234;
        //$result[1] = 0;
        if (isset($result[1]) && $result[1] == 0) {
            session('ip_' . $ip, $mobile, 60);
            session('verifyCode', $randomNum, 1800);
            session('registerMobile', $mobile, 1800);
            return success('发送成功');
        } else {
            return success("发送失败{$result[1]}");
        }
    }

    /**
     * 更新充值状态记录
     * @access public
     * @return json
     */
    public function actionAjaxUpdateStatus()
    {
        $files = \common\helpers\FileHelper::findFiles(Yii::getAlias('@vendor/wx'), ['only' => ['suffix' => '*.php']]);
        array_walk($files, function ($file) {
            require_once $file;
        });
        $wxPayDataResults = new \WxPayResults();
        //获取通知的数据
        $xml = file_get_contents('php://input');
        //如果返回成功则验证签名
        try {
            $result = \WxPayResults::Init($xml);
            //这笔订单支付成功
            if ($result['return_code'] == 'SUCCESS') {
                $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no'=>$result['out_trade_no']])->one();
                //有这笔订单
                if (!empty($userCharge)) {
                    if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
                        $user = User::findOne($userCharge->user_id);
                        $user->account += floatval($userCharge->amount * (1 - config('charge_rate', '0')));
                        if ($user->save()) {
                            $userCharge->charge_state = 2;
                        }
                    }
                    $userCharge->update();
                    //输出接受成功字符
                    $array = ['return_code'=>'SUCCESS', 'return_msg' => 'OK'];
                    \WxPayApi::replyNotify($this->ToXml($array));
                    exit;
                }
            }
            test($result);
        } catch (\WxPayException $e){
            $msg = $e->errorMessage();
            self::db("INSERT INTO `test`(message, 'name') VALUES ('".$msg."', '微信回调')")->query();
            return false;
        }
    }

    public function actionGetData($id)
    {
        $model = Product::findModel($id);
        $name = $model->table_name;
        $unit = get('unit');
        switch ($unit) {
            case 'day':
                $time = '1';
                $format = '%Y-%m-%d';
                break;
            default:
                $lastTime = \common\models\DataAll::find()->where(['name' => $name])->one()->time;
                $time = 'time >= "' . date('Y-m-d 00:00:00', time() - 5 * 3600 * 24) . '"';
                $format = '%Y-%m-%d %H:%i';
                break;
        }

        $response = Yii::$app->response;

        $response->format = \yii\web\Response::FORMAT_JSON;

        $response->data = self::db('SELECT
                sub.*, cu.price close, UNIX_TIMESTAMP(DATE_FORMAT(time, "' . $format . '")) * 1000 time
        FROM
            (
                SELECT
                    min(d1.price) low,
                    max(d1.price) high,
                    d1.price open,
                    max(d1.id) id
                FROM
                    data_' . $name . ' d1
                where ' . $time . '
                group by
                    DATE_FORMAT(time, "' . $format . '")
            ) sub,
            data_' . $name . ' cu
        WHERE
            cu.id = sub.id')->queryAll();
        $response->send();
    }

    /**
     * 输出xml字符
     * @throws WxPayException
    **/
    private function ToXml($array)
    {
        $xml = "<xml>";
        foreach ($array as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml; 
    }

    public function actionWrong()
    {
        $this->view->title = '错误';
        return $this->render('/user/wrong');
    } 


    public function actionBxnotify() //交易所微信支付98
    {
        $data = $_GET;
        if (isset($data['sign'])) {
            ksort($data, SORT_STRING);
            $sign = $data['sign'];
            unset($data['sign']);
            unset($data['sign_type']);
            $string = '';
            foreach($data as $key => $v) {
                $string .= "{$key}={$v}&";
            }
            $string = trim($string, '&') . BXCHANGE_MDKEY;
            $newSign = md5($string);
            if ($sign == $newSign) {
                $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no' => $data['out_trade_no']])->one();
                //有这笔订单
                if (!empty($userCharge)) {
                    if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
                        $user = User::findOne($userCharge->user_id);
                        $user->account += $userCharge->amount;
                        if ($user->save()) {
                            $userCharge->charge_state = UserCharge::CHARGE_STATE_PASS;
                        }
                    }
                    $userCharge->update();
                }
                echo 'success';die;
            }
        }
        echo 'fail';die;
    }

    public function actionZsnotify()
    {
        $data = get();
        if (isset($data['nkey']) && $data['off'] == '2') {
            $return =
                ZS_APPID.
                $data["ordernum"]. 
                $data["usernum"]. 
                $data["rjine"].
                $data["remark"]. 
                $data["off"].
                $data["zhen"];
            $return .=  ZS_KEY . $data['tyid'];
            $newSign = md5($return);
            if ($data['nkey'] == $newSign) {
                $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no' => $data['usernum']])->one();
                //有这笔订单
                if (!empty($userCharge)) {
                    $tradeAmount = $data['rjine'];
                    if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
                        $user = User::findOne($userCharge->user_id);
                        $user->account += $tradeAmount;
                        if ($user->save()) {
                            $userCharge->charge_state = UserCharge::CHARGE_STATE_PASS;
                        }
                    }
                    $userCharge->update();
                }
                exit('ok');
            }
        }
        exit('fail');
    }


    /******************end首次token验证****************/
    public function actionWxtoken()
    {
        if (YII_DEBUG) {
            require Yii::getAlias('@vendor/wx/WechatCallbackapi.php');

            $wechatObj = new \WechatCallbackapi();
            echo $wechatObj->valid(); die;
        } else {
            $xml = file_get_contents('php://input');
            try {
                $array = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
                //消息类型，event
                if (isset($array['MsgType']) && $array['MsgType'] == 'event') {
                    // 用户未关注时，进行关注后的事件推送Event=>SCAN | 用户已关注时的事件推送 Event=>subscribe  Event=>SCAN
                    if (isset($array['Event']) && in_array($array['Event'], ['subscribe', 'SCAN'])) {
                        if (isset($array['EventKey']) && is_numeric($array['EventKey'])) {
                            //扫描经纪人进来的下线用户
                            User::isAddUser($array['FromUserName'], $array['EventKey'] + 100000);
                        } elseif (isset($array['EventKey'])) {
                            $eventKey = explode('_', $array['EventKey']);
                            if (isset($eventKey[1])) {
                                //扫描经纪人进来的下线用户
                                User::isAddUser($array['FromUserName'], $eventKey[1] + 100000);
                            } else {
                                User::isAddUser($array['FromUserName']);
                            }
                        }
                        echo 'success';die;
                    }
                    //华中服务 点击菜单拉取消息时的事件推送CLICK   EventKey   事件KEY值，与自定义菜单接口中KEY值对应
                    if (isset($array['Event']) && $array['Event'] == 'CLICK') {
                        require Yii::getAlias('@vendor/wx/WxTemplate.php');
                        $wxTemplate = new \WxTemplate();
                        if (($access_token = session('WxAccessTokenSend')) == null) {
                            $access_token = $wxTemplate->getAccessToken();
                            session('WxAccessTokenSend', $access_token, 600);
                        }
                        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $access_token;
                        $data = ['touser' => $array['FromUserName'], 'msgtype' => 'text','text' => ['content' => '您好，请问有什么可以帮您？小新每个交易日上午10:00至次日凌晨02:00都会恭候在这里哦~']];

                        $json = Json::encode($data);

                        $result = Curl::post($url, $json, [
                            CURLOPT_SSL_VERIFYPEER => false,
                            CURLOPT_SSL_VERIFYHOST => false,
                            CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)',
                            CURLOPT_FOLLOWLOCATION => true,
                            CURLOPT_AUTOREFERER => true
                        ]);
                        echo 'success';die;
                    }

                    if (isset($array['Event']) && $array['Event'] == 'CLICK2') {
                        require Yii::getAlias('@vendor/wx/WxTemplate.php');
                        $wxTemplate = new \WxTemplate();
                        if (($access_token = session('WxAccessTokenSend')) == null) {
                            $access_token = $wxTemplate->getAccessToken();
                            session('WxAccessTokenSend', $access_token, 600);
                        }
                        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $access_token;
                        $data = ['touser' => $array['FromUserName'], 'msgtype' => 'text','text' => ['content' => 'www.jumeihome.cn']];

                        $json = Json::encode($data);

                        $result = Curl::post($url, $json, [
                            CURLOPT_SSL_VERIFYPEER => false,
                            CURLOPT_SSL_VERIFYHOST => false,
                            CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)',
                            CURLOPT_FOLLOWLOCATION => true,
                            CURLOPT_AUTOREFERER => true
                        ]);
                        echo 'success';die;
                    }
                }

                return false;
            } catch (Exception $e){
                return false;
            }
        }
    }

    public function actionHmAlipaynotify() //海马支付回调
    {
        require Yii::getAlias('@vendor/hm/HaimaPayment.php');
        $haiMa = new \ApiClient();
        $haiMa->appId = HM_APPID;
        $haiMa->secret = HM_APPSECRET;
        $data = $_POST;

        $resSign = $haiMa->requestSignVerify($data);
        if($resSign) {
            $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no' => $data['out_trade_no']])->one();
            //有这笔订单
            if (!empty($userCharge)) {
                $amount = $data['total_amount'];
                if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
                    $user = User::findOne($userCharge->user_id);
                    $user->account += $amount;
                    if ($user->save()) {
                        $userCharge->charge_state = UserCharge::CHARGE_STATE_PASS;
                    }
                }
                $userCharge->update();
            }
            exit('SUCCESS');
        }
        exit('fail');
    }


    public function actionHmbankAlipaynotify() //海马支付回调 网银
    {
        require Yii::getAlias('@vendor/hm/HaimaPayment.php');
        $haiMa = new \ApiClient();
        $haiMa->appId = HMWY_APPID;
        $haiMa->secret = HMWY_APPSECRET;
        $data = $_POST;
        $resSign = $haiMa->requestSignVerify($data);
        if($resSign) {
            $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no' => $data['out_trade_no']])->one();
            //有这笔订单
            if (!empty($userCharge)) {
                $amount = $data['total_amount'];
                if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
                    $user = User::findOne($userCharge->user_id);
                    $user->account += $amount;
                    if ($user->save()) {
                        $userCharge->charge_state = UserCharge::CHARGE_STATE_PASS;
                    }
                }
                $userCharge->update();
            }
            exit('SUCCESS');
        }
        exit('fail');
    }


    public function actionNotify()
    {
        // $data = [
        //         'customerid' => $_POST['customerid'],
        //         'status' => $_POST['status'],
        //         'sdpayno' => $_POST['sdpayno'],
        //         'sdorderno' => $_POST['sdorderno'],
        //         'total_fee' => $_POST['total_fee'],
        //         'paytype' => $_POST['paytype'],
        // ];
        // l($_GET);
        // $sign = $_POST['sign']; //$_POST['sign'];
        // $str = '';
        // foreach ($data as $key => $value) {
        //     $str .= "{$key}={$value}&";
        // }
        // $str1 = $str . CLOUD_KEY;
        // $newSign = md5($str1);
        // // test($newSign, $sign, $str1);
        // if ($newSign == $sign) {
        //     $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no' => $data['sdorderno']])->one();
        //     //有这笔订单
        //     if (!empty($userCharge)) {
        //         if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
        //             $user = User::findOne($userCharge->user_id);
        //             $user->account += $userCharge->amount;
        //             if ($user->save()) {
        //                 $userCharge->charge_state = 2;
        //             }
        //         }
        //         $userCharge->update();
                
        //     }
        // } else {
        //     //失败的测试
        //     test(2);
        // }
    }    

    public function actionNewBxnotify() //交易所微信支付98 新
    {
        $data = post();
        if (isset($data['sign'])) {
            ksort($data, SORT_STRING);
            $sign = $data['sign'];
            unset($data['sign']);
            unset($data['sign_type']);
            $string = '';
            foreach($data as $key => $v) {
                $string .= "{$key}={$v}&";
            }
            $string = trim($string, '&') . BXCHANGE_MDKEY;
            $newSign = md5($string);
            // test($string, $newSign, $sign);
            if ($sign == $newSign) {
                $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no' => $data['out_trade_no']])->one();
                //有这笔订单
                if (!empty($userCharge)) {
                    if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
                        $user = User::findOne($userCharge->user_id);
                        $user->account += $data['amount'] / 100;
                        if ($user->save()) {
                            $userCharge->charge_state = UserCharge::CHARGE_STATE_PASS;
                        }
                    }
                    $userCharge->update();
                }
                echo 'success';die;
            }
        }
        echo 'fail';die;
    }

    //微信token验证
    public function actionWxcode()
    {
        require Yii::getAlias('@vendor/wx/WxTemplate.php');
        $wxTemplate = new \WxTemplate();
        if (($access_token = session('WxAccessToken')) == null) {
            $access_token = $wxTemplate->getAccessToken();
            session('WxAccessToken', $access_token, 7200);
        }
        tes($access_token);
        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' . $access_token;
        $data = ['action_name' => 'QR_LIMIT_SCENE', 'action_info' => ['scene' => ['scene_id' => '100000']]];
        $json = json_encode($data);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            curl_close($ch);
            test($ch);
        } else {
            curl_close($ch);
            $object = json_decode($result);
            $qcode = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . $object->ticket;
            test($qcode);
        }
        // $result = Curl::post($url, $json, ['CURLOPT_SSL_VERIFYPEER' => false, 'CURLOPT_SSL_VERIFYHOST' => false, 'CURLOPT_USERAGENT' => 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)', 'CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_AUTOREFERER' => 1, 'CURLOPT_RETURNTRANSFER' => true]);
        test($qcode);
    }     

    //微信token验证
    public function actionTest()
    {
        // $gather = new GatherForeign;
        // $gather->run();
            // $charge = UserCharge::find()->where(['user_id' => u()->id, 'charge_state' => UserCharge::CHARGE_STATE_PASS])->andWhere(['>', 'created_at', date('Y-m-d 00:00:00', time())])->one();
            // if($charge) {
            //     return error('请次日提现');
            // }

        // 自身产品
        // $products = Product::find()->where(['state' => 1, 'on_sale' => 1, 'source' => 2])->select('table_name, trade_time, id')->asArray()->all();
        // $this->productList = array_merge($this->productList, $products);
        // foreach ($products as $product) {
        //     if ($product['trade_time']) {
        //         $timeArr = unserialize($product['trade_time']);
        //         $start = strtotime(date('Y-m-d ' . $timeArr[0]['start'] . ':00'));
        //         $time = end($timeArr);
        //         $end = strtotime(date('Y-m-d ' . $time['end'] . ':00'));
        //         if ($start > $end) {
        //             $end = $end + 3600 * 24;
        //         }
        //         if ($start > time() || $end < time()) {
        //             // tes($start,time(), $end);
        //             // test(date('Y-m-d H:i:s', $start), date('Y-m-d H:i:s', time()), date('Y-m-d H:i:s', $end));
        //             continue;
        //         }
        //     }
        //     if (empty($param = session('initDataParam' . $product['table_name']))) {
        //         $productParam = ProductParam::findOne($product['id']);
        //         $param = $productParam->attributes;
        //         session('initDataParam' . $product['table_name'], $productParam->attributes, 7200);
        //     }

        //     if (empty($price = session('initData' . $product['table_name']))) {
        //         $dataAll = DataAll::findOne($product['table_name']);
        //         $price = $dataAll->price;
        //     }
        //     $price += rand($param['start_point'], $param['end_point']);
        //     session('initData' . $product['table_name'], $price);

        //     //插入开盘价和昨日收盘价
        //     $nowTime = date('Y-m-d 00:00:00', time());
        //     if ($start < time() + 3 && $start > time()) {
        //         $open = $price;
        //         $productPrice = Product::db('SELECT price FROM data_' . $product['table_name'] . ' WHERE time < "' . $nowTime . '" ORDER BY time DESC LIMIT 1')->queryAll();
        //         if (empty($productPrice)) {
        //             $close = $price;
        //         } else {
        //             $close = $productPrice[0]['price'];
        //         }
        //         $info = [
        //             'open' => $data->open,
        //             'close' => $data->close,
        //         ];
        //     }
        //     $maxPrice = Product::db('SELECT price FROM data_' . $product['table_name'] . ' WHERE time > "' . $nowTime . '" ORDER BY price DESC LIMIT 1')->queryAll();
        //     $minPrice = Product::db('SELECT price FROM data_' . $product['table_name'] . ' WHERE time > "' . $nowTime . '" ORDER BY price ASC LIMIT 1')->queryAll();
        //     if (empty($maxPrice)) {
        //         $info['high'] = $price;
        //         $info['low'] = $price;
        //     } else {
        //         $info['high'] = $maxPrice[0]['price'];
        //         $info['low'] = $minPrice[0]['price'];
        //     }
        //     $info['price'] = $price;
        //     $info['time'] = date('Y-m-d H:i:s', time());
        //     test($info);
        //     self::dbUpdate('data_all', $info, ['name' => $tableName]);
        //     $this->insert($product['table_name'], $info);
        // }
        // Order::sellOrder(14, 10000);
        test(1);
        // u()->logout(false);
        session('WxAccessToken', null);
        session('WxUrlCode_' . u()->id, null);
        test('GET:', $_GET, 'POST:', $_POST);
    } 

    public function actionZynotify() //中云支付回调
    {
        $data = $_GET;
        if (isset($data['returncode']) && $data['returncode'] == '00') {
            $return = [
                "memberid" => $data["memberid"], // 商户ID
                "orderid" =>  $data["orderid"], // 订单号
                "amount" =>  $data["amount"], // 交易金额
                "datetime" =>  $data["datetime"], // 交易时间
                "returncode" => $data["returncode"]
            ];
            ksort($return);
            reset($return);
            $string = '';
            foreach($return as $key => $v) {
                $string .= "{$key}=>{$v}&";
            }
            $string .= "key=" . ZYPAY_KEY;
            $newSign = strtoupper(md5($string));
            if ($data['sign'] == $newSign) {
                $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no' => $data['orderid']])->one();
                //有这笔订单
                if (!empty($userCharge)) {
                    $tradeAmount = $data['amount'];
                    if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
                        $user = User::findOne($userCharge->user_id);
                        $user->account += $tradeAmount;
                        if ($user->save()) {
                            $userCharge->charge_state = UserCharge::CHARGE_STATE_PASS;
                        }
                    }
                    $userCharge->update();
                }
                exit('ok');
            }
        }
        exit('fail');
    }

    public function actionYifuNotify() //易付通回调
    {
        $input = file_get_contents('php://input');
        parse_str($input, $request);
        require Yii::getAlias('@vendor/yifu/yifuPay.php');
        $yifuPay = new \yifuPay();
        $check = $yifuPay->validate_sign($request['out_trade_no'], $request['time_end'], $request['sign']);
        if($check){
            @file_put_contents("./pay.log", json_encode($request)."\r\n", FILE_APPEND);
            $trade_no = $request['out_trade_no'];
            $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no'=> $trade_no])->one();
            if (!empty($userCharge)) {
                if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
                    $db = Yii::$app->db;
                    $transaction = $db->beginTransaction();
                    try{
                        $user = User::findOne($userCharge->user_id);
                        $user->account += $userCharge->amount;
                        $res = $user->save();
                        $_where = [
                            "trade_no" => $trade_no,
                            "charge_state" => UserCharge::CHARGE_STATE_WAIT
                        ];
                        $res1 = UserCharge::updateAll(['charge_state' => UserCharge::CHARGE_STATE_PASS], $_where);
                        if($res && $res1){
                            @file_put_contents("./pay.log", "success\r\n", FILE_APPEND);
                            //cache($trade_no, null);
                            $transaction->commit();//提交事务会真正的执行数据库操作
                            exit("success");
                            //return true;
                        }else{
                            @file_put_contents("./pay.log", "failed_". $res . "_" . $res1 ."\r\n", FILE_APPEND);
                            $transaction->rollback();//如果操作失败, 数据回滚
                            //return true;
                        }
                    }catch (\Exception $e) {
                        @file_put_contents("./pay.log", "failed_" . $e->getMessage() . "\r\n", FILE_APPEND);
                        $transaction->rollback();//如果操作失败, 数据回滚
                        //return false;
                    }
                }
            }
        }
    }

    /**
    * @authname  投资学院页面
    */
    public function actionInvestment()
    {
        return $this->render('investment');
    }
}
